//
//  YHclockVC.m
//  test
//
//  Created by 朱圳 on 2018/2/26.
//  Copyright © 2018年 朱圳. All rights reserved.
//

#import "YHclockVC.h"
#import "PlanModel.h"
#import "ContentModel.h"
#import "ClockTableCell.h"
#import "YHClockhead.h"
#import "ClockBottomView.h"
@interface YHclockVC ()<UITableViewDelegate,UITableViewDataSource,ClockBottomViewDelegate,ContentClickDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIView *noDataView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSMutableArray *contentArray;
@property(nonatomic,strong)NSMutableArray *contentIDArray;
@property(nonatomic,strong)PlanModel *model;
@property(nonatomic,strong)NSArray *arrStatuses;
@property (nonatomic,assign)NSUInteger counts;
@property(nonatomic,strong)NSString *days;
@end

@implementation YHclockVC


- (NSMutableArray *)dataArray {
    
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)contentArray {
    
    if(!_contentArray){
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;
}
- (NSMutableArray *)contentIDArray {
    
    if(!_contentIDArray){
        _contentIDArray = [NSMutableArray array];
    }
    return _contentIDArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.days = Days;
    
    [self.view addSubview:self.tableView];
    [self requestPlanData];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestPlanData];
    }];

}

//请求首页网络数据
-(void)requestPlanData{

    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{
                           @"sid" : Sid,
                           @"spass" : Spassword,
                           @"days" : self.days
                           };
    [[AFNetworkTool shareManager]postJSONWithUrl:Stu_Clock parmas:dict successData:^(id json) {
        [self.tableView.mj_header endRefreshing];
        if ([json[@"message"]isEqualToString:@"success"]) {
            [self.dataArray removeAllObjects];
            [self.contentArray removeAllObjects];
            self.arrStatuses = json[@"clockstatuses"];
            NSArray *arr = json[@"list"];
            self.counts = 0;
            for (NSDictionary * dic in arr) {
                self.model = [PlanModel yy_modelWithJSON:dic];
                if (self.model.list.count > 0) {
                    self.counts += 1;
                    [self.dataArray addObject:self.model];
                    for (ContentModel *content in self.model.list) {
                        [self.contentArray addObject:content];
                    }
                }
            }
            /**判断是否有数据
             */
            if (self.counts > 0) {
                NSLog(@">>>you");
//                [self.noDataView removeFromSuperview];
            }else{
                NSLog(@">>>wu");
                [self.tableView removeFromSuperview];
                [self.view addSubview:self.noDataView];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData];
        });
    } failure:^(NSError *error) {
        [Utility showFail:@"网络连接出错..."];
        NSLog(@"error%@",error);
    }];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.model = self.dataArray[section];
    return  self.model.list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ClockTableCell *cell=[ClockTableCell cellWithTableView:tableView withReuseIdentifier:@"ClockTableCellID"];
    cell.relateDelegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    self.model = self.dataArray[indexPath.section];
    cell.contentModel= self.model.list[indexPath.row];
    /**判断是否已经打卡
     */
    if (self.arrStatuses.count > 0 ) {
        [cell.clockBtn setUserInteractionEnabled:NO];
        NSString *text = self.arrStatuses[0][@"content"];
        NSArray *p = [text componentsSeparatedByString:@","];
        //升序
        [p sortedArrayUsingSelector:@selector(compare:)];
        
        for (int i = 0; i<p.count; i++) {
            if ([self.model.list[indexPath.row].contentID  isEqualToString:p[i]]) {
                [cell.clockBtn setImage:[UIImage imageNamed:@"stu-ka"] forState:UIControlStateNormal];
            }
        }
    }else{
        [cell.clockBtn setUserInteractionEnabled:YES];
    }
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    YHClockhead *head=[[YHClockhead alloc]init];
    self.model = self.dataArray[section];
    head.headcoursename.text=self.model.coursename;
    return head;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if(section==self.dataArray.count-1){
        
        ClockBottomView *foot = [[ClockBottomView alloc] initWithReuseIdentifier:@"foot"];
        foot.delegate = self;
        if (self.arrStatuses.count > 0 ) {
            [foot.clickBtn setHidden:YES];
            [foot.btn setHidden:YES];
            [foot.label setHidden:YES];
            [foot.text setUserInteractionEnabled:NO];
            NSString *version = [NSString stringWithFormat:@"%@",self.arrStatuses[0][@"version"]];
            //     NSLog(@">>>%@", version);
            if ([version isEqualToString:@"<null>"] || [version isEqualToString:@""]) {
                [foot.text setHidden:YES];
            }
            foot.text.text = version;
        }
        //判断是否全选
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            BOOL allSelected = YES;
            for (PlanModel *model in self.dataArray) {
                for (ContentModel *content in model.list) {
                    if (!content.isChecked) {
                        allSelected = NO;
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                ContentModel * model = [[ContentModel alloc]init];
                model.isChecked = allSelected;
                foot.contentModel = model;
            });
        });
        return foot;
    }else{
        return nil;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == (self.dataArray.count-1)) {
        return 160;
    }else{
        return CGFLOAT_MIN;
    }
}

-(void)ClockBtn:(UIButton *)sender withversion:(NSString *)version{
    NSString * content = [self.contentIDArray componentsJoinedByString:@","];
    if ([content isEqualToString:@""]) {
        [Utility showFail:@"还未选取打卡内容"];
    }else{
        NSDictionary *dict = @{
                               @"sid" : Sid,
                               @"spass" : Spassword,
                               @"days" : self.days,
                               @"content" : content,
                               @"version" : version
                               };
//        NSLog(@">>>%@", dict);
        
        [[AFNetworkTool shareManager]postJSONWithUrl:Stu_SetClock parmas:dict successData:^(id json) {
            [self requestPlanData];
            [Utility showSuccess:@"打卡成功"];
        } failure:^(NSError *error) {
            [Utility showFail:@"服务器出错"];
        }];
        [self.tableView reloadData];
    }
}
/**
 全选
 */
-(void)selectedAll:(UIButton *)sender withModel:(ContentModel *)model{
    [self.contentIDArray removeAllObjects];
    if (model.isChecked) {
        for (PlanModel *model in self.dataArray) {
            for (ContentModel *content in model.list) {
                content.isChecked = YES;
                [self.contentIDArray addObject:content.contentID];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }else{
        for (PlanModel *model in self.dataArray) {
            for (ContentModel *content in model.list) {
                content.isChecked = NO;
                [self.contentIDArray removeObject:content.contentID];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }
}

/**
 选择打卡内容
 @param model ContentModel模型
 */
-(void)clockAction:(UIButton *)sender withModel:(ContentModel *)model{
    if (model.isChecked) {
        [self.contentIDArray addObject:model.contentID];
    }else{
        [self.contentIDArray removeObject:model.contentID];
    }
    [self.tableView reloadData];
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;

    }
    return _tableView;
}

-(UIView *)noDataView{
    
    if (!_noDataView) {
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height-48)];
        _noDataView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.image = [UIImage imageNamed:@"NoData"];
        [_noDataView addSubview:imageView];
        
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.noDataView);
            make.top.mas_equalTo(100);
            make.width.mas_equalTo(100);
            make.height.mas_equalTo(100);
        }];
        UILabel * la = [[UILabel alloc]init];
        la.text = @"亲,暂时没有打卡信息!";
        la.textColor = [UIColor darkGrayColor];
        la.textAlignment = NSTextAlignmentCenter;
        [_noDataView addSubview:la];
        [la mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.noDataView);
            [make.top.mas_equalTo(imageView.mas_bottom) setOffset:10];
            make.width.mas_equalTo(200);
        }];
    }
    return _noDataView;
}

@end
